<template>
  <div class="operation-log">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="操作人">
          <el-input
            v-model="searchForm.operator"
            placeholder="请输入操作人"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择操作类型"
            clearable
            class="search-select"
          >
            <el-option label="新增" value="create" />
            <el-option label="修改" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
            <el-option label="导入" value="import" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            class="search-select"
          >
            <el-option label="成功" value="success" />
            <el-option label="失败" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="search-date"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="danger" @click="handleClearAll">
          <el-icon><Delete /></el-icon>清空日志
        </el-button>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>导出日志
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><RefreshRight /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 日志列表 -->
    <el-card shadow="hover">
      <el-table
        :data="logList"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="operator" label="操作人" show-overflow-tooltip />
        <el-table-column prop="type" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" show-overflow-tooltip />
        <el-table-column prop="description" label="操作描述" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="130" show-overflow-tooltip />
        <el-table-column prop="location" label="操作地点" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="操作时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip content="详情" placement="top">
                <el-button type="primary" link @click="handleView(row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="日志详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作人">
          {{ currentLog?.operator }}
        </el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getTypeTag(currentLog?.type)">
            {{ getTypeName(currentLog?.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作模块">
          {{ currentLog?.module }}
        </el-descriptions-item>
        <el-descriptions-item label="操作描述">
          {{ currentLog?.description }}
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">
          {{ currentLog?.ip }}
        </el-descriptions-item>
        <el-descriptions-item label="操作地点">
          {{ currentLog?.location }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentLog?.status === 'success' ? 'success' : 'danger'">
            {{ currentLog?.status === 'success' ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">
          {{ currentLog?.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="请求方法" :span="2">
          {{ currentLog?.method }}
        </el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2">
          <el-input
            type="textarea"
            :model-value="currentLog?.params"
            rows="3"
            readonly
          />
        </el-descriptions-item>
        <el-descriptions-item 
          v-if="currentLog?.status === 'error'"
          label="错误信息" 
          :span="2"
        >
          <el-input
            type="textarea"
            :model-value="currentLog?.error"
            rows="3"
            readonly
          />
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, RefreshLeft, Delete, Download, RefreshRight,
  View
} from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'

// 日志项接口
interface LogItem {
  id: string | number
  operator: string
  type: string
  module: string
  description: string
  method: string
  params: string
  ip: string
  location: string
  status: 'success' | 'error'
  error?: string
  createTime: string
}

// 搜索表单
const searchForm = ref({
  operator: '',
  type: '',
  status: '',
  timeRange: []
})

// 分页配置
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 状态定义
const loading = ref(false)
const dialogVisible = ref(false)
const currentLog = ref<LogItem | null>(null)
const logList = ref<LogItem[]>([])
const selectedLogs = ref<LogItem[]>([])

const router = useRouter()
const route = useRoute()

// 获取操作类型标签样式
const getTypeTag = (type?: string) => {
  const map: Record<string, string> = {
    create: 'success',
    update: 'warning',
    delete: 'danger',
    export: 'info',
    import: 'info'
  }
  return map[type || ''] || 'info'
}

// 获取操作类型名称
const getTypeName = (type?: string) => {
  const map: Record<string, string> = {
    create: '新增',
    update: '修改',
    delete: '删除',
    export: '导出',
    import: '导入'
  }
  return map[type || ''] || '未知'
}

// 处理搜索
const handleSearch = () => {
  page.value.current = 1
  fetchLogList()
}

// 处理重置
const handleReset = () => {
  searchForm.value = {
    operator: '',
    type: '',
    status: '',
    timeRange: []
  }
  handleSearch()
}

// 处理查看详情
const handleView = (row: LogItem) => {
  currentLog.value = row
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: LogItem) => {
  ElMessageBox.confirm(
    '确定要删除该日志吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用删除接口
    ElMessage.success('删除成功')
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请选择要删除的日志')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedLogs.value.length} 条日志吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用批量删除接口
    ElMessage.success('批量删除成功')
  })
}

// 处理清空日志
const handleClearAll = () => {
  ElMessageBox.confirm(
    '确定要清空所有日志吗？该操作不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用清空接口
    ElMessage.success('清空成功')
  })
}

// 处理导出
const handleExport = () => {
  // 这里调用导出接口
  ElMessage.success('导出成功')
}

// 处理刷新
const handleRefresh = () => {
  fetchLogList()
}

// 处理表格选择变化
const handleSelectionChange = (selection: LogItem[]) => {
  selectedLogs.value = selection
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  page.value.size = size
  fetchLogList()
}

// 处理页码变化
const handleCurrentChange = (current: number) => {
  page.value.current = current
  fetchLogList()
}

// 获取日志列表
const fetchLogList = () => {
  loading.value = true
  // 这里调用获取日志列表接口
  setTimeout(() => {
    // 模拟数据
    logList.value = [
      {
        id: 1,
        operator: '管理员',
        type: 'create',
        module: '用户管理',
        description: '新增用户：张三',
        method: 'POST /api/user',
        params: '{"username": "zhangsan", "role": "admin"}',
        ip: '192.168.1.1',
        location: '广东省深圳市',
        status: 'success',
        createTime: '2024-01-01 12:00:00'
      },
      {
        id: 2,
        operator: '系统管理员',
        type: 'update',
        module: '角色管理',
        description: '修改角色：管理员',
        method: 'PUT /api/role',
        params: '{"id": 1, "permissions": ["user:manage"]}',
        ip: '192.168.1.2',
        location: '北京市朝阳区',
        status: 'success',
        createTime: '2024-01-01 13:00:00'
      },
      {
        id: 3,
        operator: '测试人员',
        type: 'delete',
        module: '菜单管理',
        description: '删除菜单：测试菜单',
        method: 'DELETE /api/menu',
        params: '{"id": 100}',
        ip: '192.168.1.3',
        location: '上海市浦东新区',
        status: 'error',
        error: '该菜单下有子菜单，无法删除',
        createTime: '2024-01-01 14:00:00'
      },
      {
        id: 4,
        operator: '运维人员',
        type: 'export',
        module: '日志管理',
        description: '导出操作日志',
        method: 'GET /api/logs/export',
        params: '{"startTime": "2024-01-01", "endTime": "2024-01-31"}',
        ip: '192.168.1.4',
        location: '广州市天河区',
        status: 'success',
        createTime: '2024-01-01 15:00:00'
      },
      {
        id: 5,
        operator: '管理员',
        type: 'import',
        module: '用户管理',
        description: '导入用户数据',
        method: 'POST /api/users/import',
        params: '{"file": "users.xlsx"}',
        ip: '192.168.1.5',
        location: '深圳市南山区',
        status: 'success',
        createTime: '2024-01-01 16:00:00'
      }
    ]
    page.value.total = 100
    loading.value = false
  }, 500)
}

// 修改路由监听
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/system/logs') {  // 修改这里，与路由路径匹配
      fetchLogList()
    }
  }
)

// 修改初始化检查
onMounted(() => {
  if (route.path === '/system/logs') {  // 修改这里，与路由路径匹配
    fetchLogList()
  }
})
</script>

<style lang="scss" scoped>
.operation-log {
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 16px;
    }
    
    .search-input {
      width: 200px;
    }
    
    .search-select {
      width: 160px;
    }
    
    .search-date {
      width: 360px;
    }
  }
  
  .toolbar {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    gap: 16px;
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }
  
  .el-card {
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
  }
  
  .el-table {
    border-radius: 8px;
    overflow: hidden;
    
    :deep(.el-button-group) {
      .el-button {
        padding: 4px 8px;
        
        .el-icon {
          font-size: 16px;
        }
        
        &:hover {
          .el-icon {
            transform: scale(1.2);
          }
        }
      }
    }
  }
  
  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.el-tag) {
    border-radius: 4px;
    
    &.el-tag--success {
      background: var(--el-color-success-light-9);
    }
    
    &.el-tag--warning {
      background: var(--el-color-warning-light-9);
    }
    
    &.el-tag--danger {
      background: var(--el-color-danger-light-9);
    }
    
    &.el-tag--info {
      background: var(--el-color-info-light-9);
    }
  }
}
</style> 